<?php


class VerifyCode
{
	private $width;
	private $height;
	private $code_num;		//验证码数量
	private $type;			//1：字母和数字混合，2：纯数字，3：纯字母
	private $point_num;		//干扰点数量
	private $fontsize;		//字体大小
	private $image;			//验证码图片
	private $rand_str;
	
	function __construct($params=[])
	{
		if(empty($params)){
			$this->width 		= 	100;
			$this->height 		= 	45;
			$this->code_num 	= 	4;
			$this->type 		= 	1;
			$this->point_num 	= 	50;
			$this->fontsize 	= 	24;
		}else{
			$this->width 		= 	$params['width'] ?? 100;
			$this->height 		= 	$params['height'] ?? 45;
			$this->code_num 	= 	$params['code_num'] ?? 4;
			$this->type 		= 	$params['type'] ?? 1;
			$this->point_num 	= 	$params['point_num'] ?? 50;
			$this->fontsize 	= 	$params['fontsize'] ?? 24;
		}
	}

	public function renden(){
		//创建画布
		$this->image = $this->createImage();
		//生成随机验证码
		$this->randCode();
		//填充背景颜色
		imagefilledrectangle($this->image,0,0,$this->width,$this->height,$this->lightColor());
		//写入文字
		$this->write();
		//干扰线
		$this->line();
		//干扰点
		$this->point();
		//指定输出类型
		header("Content-type:image/png");
		//输出图片
		imagepng($this->image);
		//销毁
		imagedestroy($this->image);

	}

	//创建画布
	private function createImage(){
		return imagecreatetruecolor($this->width, $this->height);
	}

	//浅色
	private function lightColor(){
		return imagecolorallocate($this->image,mt_rand(130,255),mt_rand(130,255),mt_rand(130,255));
	}

	//深色
	private function darkColor(){
		return imagecolorallocate($this->image,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
	}

	//验证码
	private function randCode(){

		if($this->type == 2){
			$str = '0123456789';
			$this->rand_str = substr(str_shuffle($str), 0,$this->code_num);
		}else if($this->type == 3){
			$str_arr = range('a','z');
			shuffle($str_arr);
			$slice_arr = array_slice($str_arr, 0,$this->code_num);
			$this->rand_str = join('',$slice_arr);
		}else{
			$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$this->rand_str = substr(str_shuffle($str), 0,$this->code_num);
		}

		return $rand_str;
	}

	//写入文字
	private function write(){
		for ($i=0; $i < $this->code_num; $i++) { 
			$x = floor($this->width / $this->code_num) * $i + 5;
			$y = mt_rand($this->fontsize,$this->height);
			//绝对路径，不能有中文路径包括字体文件名
			$fontpath = 'D:/phpstudy_pro/WWW/aa.ttf';
			imagefttext($this->image,$this->fontsize,mt_rand(-20,20),$x,$y,$this->darkColor(),$fontpath,$this->rand_str[$i]);
		}
	}

	//写入干扰线
	private function line(){
		for ($i=0; $i < $this->code_num; $i++) { 
			imagearc($this->image, mt_rand(10,$this->width), mt_rand(10,$this->height)
				, mt_rand(10,$this->width), mt_rand(10,$this->height)
				, mt_rand(0,10), mt_rand(10,270), $this->lightColor());
		}
	}

	//写入干扰点
	private function point(){
		for ($i=0; $i < $this->point_num; $i++) { 
			imagesetpixel($this->image, mt_rand(0,$this->width), mt_rand(0,$this->height), $this->darkColor());
		}
	}
}

$verifyCode = new VerifyCode();
$verifyCode->renden();